# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\single_instance.py
__author__ = "Attila Gerendi (Sanyi)"
import logging, os, sys, tempfile, platform

logger = logging.getLogger("application.singleton")


class SingleInstanceException(BaseException):
    pass


class SingleInstance(object):
    def __init__(self, application_id):
        self.lockfile = os.path.join(tempfile.gettempdir(), application_id)
        logger.debug("SingleInstance lockfile: " + self.lockfile)
        if platform.system() == "Windows":
            try:
                if os.path.exists(self.lockfile):
                    os.unlink(self.lockfile)
                self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
            except OSError as e:
                t, er, tb = sys.exc_info()
                if er.errno == 13:
                    logger.error("Another instance is already running, quitting.")
                    raise SingleInstanceException() from e
                raise

        else:
            import fcntl

            self.fp = open(self.lockfile, "w")
            self.fp.flush()
            try:
                fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError as e:
                logger.error("Another instance is already running, quitting.")
                raise SingleInstanceException() from e

            self.initialized = True
